<?php
namespace App\Services;

use App\Events\CronProcessingEvent;
use App\Models\CronModel;
use App\Models\CronLogModel;
use Carbon\Carbon;
use Framework\BaseService;
use Psr\Log\LoggerInterface;

class CronService extends BaseService
{
    /**
     * 执行任务
     */
    public function execute()
    {

        $list = CronModel::query()
            ->where('execute_time', '<=', Carbon::now())
            ->where('is_free', 0)
            ->get();
        if (!empty($list)) {
            foreach ($list as $k => $v) {
                try {
                    $res = event(new CronProcessingEvent($v['event'], $v['relate_id']));
                } catch (\Exception $e) {
                    //这里要加日志
                    app(LoggerInterface::class)->error('cron运行错误:'. $e->getMessage());
                    return  $e;

                }
                //调试开启
                $data_log = [
                    'name'         => $v['name'],
                    'event'        => $v['event'],
                    'execute_time' => Carbon::now(),
                    'relate_id'    => $v['relate_id'],
                    'message'      => json_encode($res),
                    'created_at'      => Carbon::now(),
                ];

                CronLogModel::query()->insert($data_log);
                //循环任务
                CronModel::query()->where(['id'=>$v['id']])->delete();
            }
        }
        return '没有可执行数据';
    }
}
